package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.view.KeyboardUtil;
import cn.com.xinjinfu.pdoulcProduct.view.MyCallback;
import cn.com.xinjinfu.pdoulcProduct.widget.GestureEditActivity;

/**
 * 设置密码页
 * Created by android-adt on 2016/1/7.
 */
public class ActPasswordSet extends BaseActivity implements View.OnClickListener{
    private boolean isbuttonPwd;
    private Button button_pwd;
    private PopupWindow popWindow;
    private RelativeLayout rl_shoushi_pwd;
    private RequestQueue requen;

    private Context ctx;
    private Activity act;
    private EditText edit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_password_set);

        ctx = this;
        act = this;

        //初始化头布局
        TitleManager.showTitleWhite(this, "密码", "");
        requen = Volley.newRequestQueue(this);
        RelativeLayout rl_login_pwd = (RelativeLayout) findViewById(R.id.rl_login_pwd);
        rl_shoushi_pwd = (RelativeLayout) findViewById(R.id.rl_shoushi_pwd);
        button_pwd = (Button) findViewById(R.id.button_pw);
        pswchark();
        rl_login_pwd.setOnClickListener(this);
        rl_shoushi_pwd.setOnClickListener(this);
        button_pwd.setOnClickListener(this);

    }

    public void pswchark(){
        if (!SharedPreferencesUtils.getPwdBoolean(ActPasswordSet.this, "is_ok", false)){
            button_pwd.setBackgroundResource(R.drawable.btn_off);
            rl_shoushi_pwd.setVisibility(View.GONE);
            findViewById(R.id.xian).setVisibility(View.GONE);
        }else {
            button_pwd.setBackgroundResource(R.drawable.btn_on);
            rl_shoushi_pwd.setVisibility(View.VISIBLE);
            findViewById(R.id.xian).setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        pswchark();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_login_pwd:
                startActivity(new Intent(this, ActivityChangPsword.class));
                break;
            case R.id.rl_shoushi_pwd:
                showPopup();
//                popupInputMethodWindow();
//                KeyboardUtil caller = new KeyboardUtil(customView, ctx, et_pwd);
//                caller.showKeyboard();
                break;
            case R.id.button_pw:
                if (SharedPreferencesUtils.getPwdBoolean(ActPasswordSet.this, "is_ok", false)){
                    L.d("取消手势密码");
                    button_pwd.setBackgroundResource(R.drawable.btn_off);
                    rl_shoushi_pwd.setVisibility(View.GONE);
                    findViewById(R.id.xian).setVisibility(View.GONE);
                    SharedPreferencesUtils.savePwdBoolean(ActPasswordSet.this, "is_ok", false);
                    SharedPreferencesUtils.saveUserInfo(ActPasswordSet.this, "mShoushiPassword", "");
                }else {
                    showPopup();
//                    popupInputMethodWindow();
                }
                break;
            default:
                break;
        }
    }
    private View customView;
    private EditText et_pwd;
    private String pwd;
    private TextView tv_error_hint;
    private void showPopup(){
        if (popWindow == null) {
            // 获取自定义布局文件pop.xml的视图
            customView = getLayoutInflater().inflate(R.layout.popwindow_pws,
                    null, false);
            // 屏幕宽度（像素）
            DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);
            int width = metric.widthPixels;
            int height = metric.heightPixels;
            // 创建PopupWindow实例
            popWindow = new PopupWindow(customView, width, height-630);
        }
        //设置背景为半透明
        WindowManager.LayoutParams params=this.getWindow().getAttributes();
        params.alpha=0.7f;
        this.getWindow().setAttributes(params);
        //popupwindow弹出时的动画
        popWindow.setAnimationStyle(R.style.AnimationFade1);
        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(false);
        //软键盘不会挡着popupwindow
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置菜单显示的位置
        popWindow.showAtLocation(findViewById(R.id.button_pw), Gravity.BOTTOM, 0, 0);
        //关闭窗口
        ImageView img_search = (ImageView)customView.findViewById(R.id.img_search);
        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopupWindow();
            }
        });

        tv_error_hint = (TextView) customView.findViewById(R.id.tv_error_hint);

        et_pwd = (EditText) customView.findViewById(R.id.et_pwd);

        KeyboardUtil caller = new KeyboardUtil(customView, ctx, et_pwd);
        /**
         * 监听软件盘的确定键
         * */
        caller.setCallFunc(new MyCallback() {
            @Override
            public void func() {
                pwd = et_pwd.getText().toString();
                if (!TextUtils.isEmpty(et_pwd.getText())){
                    loginResult();
                }else {
                    tv_error_hint.setText("密码不能为空哦！");
                }
            }
        });
        et_pwd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0);
                }
                return true;
            }
        });
    }

    /**
     * 关闭窗口
     */
    private void closePopupWindow()
    {
        if (popWindow != null && popWindow.isShowing()) {
            popWindow.dismiss();
            popWindow = null;
            WindowManager.LayoutParams params=this.getWindow().getAttributes();
            params.alpha=1f;
            this.getWindow().setAttributes(params);
        }
    }

    public void loginResult(){
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1403");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("type", "1");
            parameters.put("passwd", DataHandler.encrypt3DES(pwd));
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters),null,succeedRespon,null);
            requen.add(request);
        }
    }
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            //密码正确，关闭窗口
            try {
                if ((int)jobj.get("code")==-1){
                    closePopupWindow();
                    Intent intent = new Intent(ActPasswordSet.this, GestureEditActivity.class);
                    startActivity(intent);
                }else {
                    tv_error_hint.setText("密码有误，请重新输入!");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
}
